<template>
  <div class="baseinfobox">
    <el-divider content-position="left">基本信息</el-divider>
    <el-form
      ref="ruleForm"
      :model="addgoodsinfo.goods"
      :rules="rules"
      class="demo-ruleForm"
      label-width="100px"
    >
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="addgoodsinfo.goods.sort"
          controls-position="right"
          size="small"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="商品编码" prop="code">
        <el-input v-model="addgoodsinfo.goods.code"></el-input>
      </el-form-item>

      <el-form-item label="商品名称" required>
        <!-- <el-switch v-model="addgoodsinfo.goods.delivery"></el-switch> -->

        <el-col :span="11">
          <el-form-item prop="name">
            <el-input v-model="addgoodsinfo.goods.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :offset="1" :span="1" class="line">——</el-col>
        <el-col :span="30">
          <el-form-item prop="unit">
            <el-input
              v-model="addgoodsinfo.goods.unit"
              placeholder="单位 如:个/件/包"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="副标题" prop="subtitle">
        <el-input
          v-model="addgoodsinfo.goods.subtitle"
          type="textarea"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="商品短标题" prop="shorttitle">
        <el-input v-model="addgoodsinfo.goods.shorttitle"></el-input>
      </el-form-item> -->
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="addgoodsinfo.goods.keyword"></el-input>
      </el-form-item>
    </el-form>

    <el-divider content-position="left">商品信息</el-divider>

    <el-form
      ref="ruleForm"
      :model="addgoodsinfo.goods"
      :rules="rules"
      class="demo-ruleForm"
      label-width="100px"
    >
      <el-form-item label="商品分类" required>
        <el-cascader
          :options="options"
          :show-all-levels="false"
          @change="optionsID"
          v-model="catgeory"
        ></el-cascader>
      </el-form-item>

      <el-form-item label="商品属性" prop="attributes1">
        <el-checkbox-group v-model="attributes1" @change="checkbox">
          <el-checkbox
            v-for="item in checkList"
            :key="item.code"
            :label="item.code"
            :value="item.code"
            >{{ item.value }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="商品价格" required>
        <el-input-number
          v-model="addgoodsinfo.goods.priceCurrent"
          controls-position="right"
          size="small"
        ></el-input-number>
        元
        <strong style="margin-left: 15px">原价</strong>
        <el-input-number
          v-model="addgoodsinfo.goods.price"
          controls-position="right"
          size="small"
        ></el-input-number>
        元
        <strong style="margin-left: 15px">成本价</strong>
        <el-input-number
          v-model="addgoodsinfo.goods.priceCost"
          controls-position="right"
          size="small"
        ></el-input-number>
        元
      </el-form-item>

      <el-form-item label="商品缩略图">
        <el-upload
          :key="uploadKey1"
          :action="uploadURL"
          list-type="picture-card"
          :show-file-list="true"
          :auto-upload="true"
          :on-success="picturesuccess1"
          :before-upload="picturebefore1"
          :on-error="pictureerror1"
          :on-exceed="pictureexceed1"
          :limit="1"
          :file-list="fileList1"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.imgUrl"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <!-- <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview1(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span> -->
              <span
                v-if="!disabled1"
                class="el-upload-list__item-delete"
                @click="handleRemove1(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible1">
          <img width="100%" :src="dialogImageUrl1" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="商品封面">
        <el-upload
          :key="uploadKey2"
          :action="uploadURL"
          :file-list="fileList2"
          list-type="picture-card"
          :show-file-list="true"
          :auto-upload="true"
          :on-success="picturesuccess2"
          :before-upload="picturebefore2"
          :on-error="pictureerror2"
          :on-exceed="pictureexceed2"
          :limit="4"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.imgUrl"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <!-- <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview2(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span> -->
              <span
                v-if="!disabled1"
                class="el-upload-list__item-delete"
                @click="handleRemove2(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible1">
          <img width="100%" :src="dialogImageUrl1" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="已出售数">
        <el-input
          v-model="addgoodsinfo.goods.sales"
          :style="{ width: '300px' }"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-divider content-position="left">商品属性</el-divider>

    <el-form
      ref="ruleForm"
      :model="addgoodsinfo.goods"
      :rules="rules"
      class="demo-ruleForm"
      label-width="100px"
    >
      <el-form-item label="单品满额包邮">
        <el-input
          v-model="addgoodsinfo.goods.priceStamp"
          :style="{ width: '200px' }"
        >
          <template slot="prepend">满</template>
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="运费设置">
        <el-input
          v-model="addgoodsinfo.goods.postage"
          :style="{ width: '200px' }"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="开发票">
        <!-- <div class="switchinvoice"> -->
        <el-switch
          :active-value="1"
          :inactive-value="0"
          class="switchinvoice"
          v-model="Invoice"
          active-text="显示"
          inactive-text="隐藏"
          @change="isInvoicehandle"
        ></el-switch>
        <!-- </div> -->
      </el-form-item>

      <el-form-item label="商品状态">
        <div class="productstatus">
          <i class="el-icon-s-opportunity"></i>
          下架商品将添加到待上架中。下架商品时请谨慎操作，确保商品没有正在被其他功能模块使用！
        </div>
        <div style="margin-top: 10px">
          <el-radio-group
            v-model="productstatusradio"
            size="medium"
            @input="productstatusradiohanle"
          >
            <el-radio-button label="上架"></el-radio-button>
            <el-radio-button label="下架"></el-radio-button>
          </el-radio-group>
        </div>
      </el-form-item>

      <el-form-item label="是否屏蔽搜索">
        <!-- <div class="switchinvoice"> -->
        <el-switch
          :active-value="1"
          :inactive-value="0"
          class="switchinvoice"
          v-model="blocksearch"
          active-text="是"
          inactive-text="否"
          @change="blocksearchhandle"
        ></el-switch>
        <!-- </div> -->
      </el-form-item>

      <el-form-item label="支持退换货">
        <!-- <div class="switchinvoice"> -->
        <el-switch
          :active-value="1"
          :inactive-value="0"
          class="switchinvoice"
          v-model="exchangepurchase"
          active-text="支持"
          inactive-text="关闭"
          @change="exchangepurchasehandle"
        ></el-switch>
        <!-- </div> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getTemplate,
  importData as importAPI,
  exportData,
  exportSelectedData,
} from "@/framework/components/dialog-column/importExport";
import { cloud } from "@/framework/utils/request";
import { getToken } from "@/framework/utils/auth";
import {
  addGoods,
  getCategoryList,
  getGoodsType,
} from "@/api/mallApi/goodsOnsell/goodsOnsell";

export default {
  name: "GoodsInfoBase",
  props: {
    addgoodsinfo: {
      type: Object,
      required: true,
    },
    enterType: Number,
  },
  data() {
    return {
      catgeory: [],
      uploadKey1: 0,
      uploadKey2: 0,
      fileList1: [],
      // fileURL:[],
      dialogImageUrl1: "",
      dialogVisible1: false,
      disabled1: false,
      fileList2: [],
      dialogImageUrl2: "",
      dialogVisible2: false,
      disabled2: false,
      uploadURL:
        process.env.VUE_APP_BASE_API +
        cloud.file +
        "/sysFileInfo/upload?secretFlag=N&fileBucket=mall",
      options: [],
      checkList: [],
      productstatusradio: "上架",
      attributes1: [],
      Invoice: 0, //开发票
      blocksearch: 0, //屏蔽搜索
      exchangepurchase: 0, //支持退换货
      ruleForm: {
        id: 0,
        mallCode: null, //门店编码
        code: null, //商品编码
        name: null, //商品名称
        subtitle: null, //商品副标题
        abbr: null, //商品简称
        unit: null, //商品单位
        sort: 0, //序号
        keyword: null, //关键字
        type: 1, //商品类型rn 1：实体商品；rn 2：虚拟商品；rn 3：虚拟物品(卡密)
        parentCategoryId: 0, //一级分类id
        categoryId: 0, //商品分类ID
        attributes: "", //1：推荐；2：新品；3：热卖；4：包邮；5：不参与会员折扣；
        priceCurrent: 0, //商品当前的出售价格
        price: 0, //商品原价
        priceCost: 0, //商品成本价
        priceHandsel: 0, //定金
        sales: 0, //销量
        priceStamp: 0, //包邮金额即满额包邮金额；空或0默认为不参与满额包邮
        postage: 0, //邮费
        tagsDefault: null, //默认标签：1：正品保证；2：7天无理由退换货；3：保修；
        tageCustomIds: null, //自定义标签ID；逗号隔开
        stock: 0, //库存
        isShowStock: 0, //是否显示库存：0：否；1：是；默认为0
        inventoryReductionType: 0, //减库存的类型 1：下单减库存；2：付款减库存；3：永不减库存；默认为1；
        details: null, //商品详情
        buyNotes: null,
        isUseSpecification: 0, //是否启用规格参数 0：否；1：是；默认为0
        isAudit: 0, //是否待审核；1：是；0：否；默认：0
        isDelete: 0, //是否删除；1：是；0：否；默认：0
        isAlwaysDelete: 0, //是否彻底删除；0：否；1：是；默认为0
        status: 0, //商品状态 1：下架；2：上架；默认为1；
        ptStatus: 0, //商品状态 1：待审核2：审核通过3：驳回 4：违规下架
        checkReason: null, //驳回理由
        shareMaterialDescribe: "", //分享素材描述
        shareMaterialContent: "", //分享素材内容
        goodsType: 1, //商品类型：1：普通商品；2：团购商品；3：服务类商品
        viewNum: 0, //浏览量
        status: 1, //商品状态 0 下架 1上架默认1

        isHideSearching: 0, //是否屏蔽搜索 0 否 1 是默认0

        isRejected: 1, //是否支持退换货 0 不支持 1 支持默认1
        imgList: [], //商品封面图
        thumb: null, //商品缩略图

        isInvoice: 0, //开发票
        category: null,
      },
      rules: {
        name: [
          //商品名称
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 1,
            max: 18,
            message: "长度在 1 到 18个字符",
            trigger: "blur",
          },
        ],
        unit: [
          //商品名称
          { required: true, message: "请输入商品单位", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        code: [
          //商品编码
          { required: true, message: "请输入商品编码", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
        keyword: [
          //关键字
          { required: true, message: "请输入商品关键字", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        attributes1: [
          //1：推荐；2：新品；3：热卖；4：包邮；5：不参与会员折扣；
          { required: true, message: "请选择商品属性", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "至少一个",
            trigger: "blur",
          },
        ],
        subtitle: [
          //商品副标题
          { required: true, message: "请输入商品副标题", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getAttribute();
    this.catgeory = [
      this.addgoodsinfo.goods.parentCategoryId,
      this.addgoodsinfo.goods.categoryId,
    ];
    this.$nextTick(() => {
      if (this.enterType === 1) {
        this.fileList1 = [];
        this.fileList2 = [];
      } else if (this.enterType === 2) {
      }
    });
    this.addgoodsinfo.imgList.map((item) => {
      this.fileList2.push({ imgUrl: item.img });
    });
    this.fileList1.push({ imgUrl: this.addgoodsinfo.goods.thumb });
  },
  created() {
    this.getGoodsTypeList();
    this.getAttribute();

    if (this.enterType === 1) {
      this.fileList1 = [];
      this.fileList2 = [];
    } else if (this.enterType === 2) {
      this.attributes1 = this.addgoodsinfo.goods.attributes.split(",");
      if (this.addgoodsinfo.goods.status === 2) {
        this.productstatusradio = "上架";
      }
      if (this.addgoodsinfo.goods.status === 1) {
        this.productstatusradio = "下架";
      }
      this.Invoice = this.addgoodsinfo.goods.isInvoice; //开发票
      this.blocksearch = this.addgoodsinfo.goods.isHideSearching; //屏蔽搜索
      this.exchangepurchase = this.addgoodsinfo.goods.isRejected; //支持退换货
    }
  },
  methods: {
    //商品图片
    picturesuccess1(response, file, fileList) {
      this.fileList1 = [{ imgUrl: response.data.fileUrl }];
      this.addgoodsinfo.goods.thumb = response.data.fileUrl;
    },
    pictureerror1(response, file, fileList) {},
    picturebefore1(file) {
      const isJPG = file.type === "image/jpeg" || "image/png" || "image/jpg";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("商品缩略图只能是 JPG,PNG,JPEG 格式!");
      }
      if (!isLt10M) {
        this.$message.error("商品缩略图大小不能超过10MB!");
      }
      this.uploadKey1 += 1;
      return isJPG && isLt10M;
    },
    pictureexceed1(files, fileList) {
      if (fileList.length >= 1) {
        this.$message.error("商品缩略图最多上传1张!");
      }
    }, //图片限制提示
    handleRemove1(file) {
      // Remove the selected file from the fileList
      const index = this.fileList1.indexOf(file);
      if (index !== -1) {
        this.fileList1.splice(index, 1);
      }
    },
    handlePictureCardPreview1(file) {
      this.dialogImageUrl1 = file.url;
      this.dialogVisible1 = true;
    },
    //封面图片
    picturesuccess2(response, file, fileList) {
      file.imgUrl = response.data.fileUrl;
      this.addgoodsinfo.imgList.push({
        goodsId: null,
        mallCode: null,
        type: "cover_photo",
        img: response.data.fileUrl,
      });

      this.fileList2.push({
        imgUrl: response.data.fileUrl,
      });
      //console.log(response);

      //console.log("fileList", fileList);
    },
    pictureerror2(response, file, fileList) {},
    picturebefore2(file) {
      const isJPG = file.type === "image/jpeg" || "image/png" || "image/jpg";
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("商品封面图只能是 JPG,PNG,JPEG 格式!");
      }
      if (!isLt10M) {
        this.$message.error("商品封面图大小不能超过10MB!");
      }
      this.uploadKey2 += 1;
      return isJPG && isLt10M;
    }, //图片大小格式校验
    pictureexceed2(files, fileList) {
      if (fileList.length >= 4) {
        this.$message.error("图片最多上传4张!");
      }
    }, //图片限制提示
    handleRemove2(file) {
      // 移除图片
      const index = this.fileList2.indexOf(file);
      if (index !== -1) {
        this.fileList2.splice(index, 1);
      }
      //判断移除的 url是否存在 参数中，如果存在 则删除
      const imgIndex = this.addgoodsinfo.imgList.findIndex(
        (img) => img.img === file.imgUrl
      );

      if (imgIndex !== -1) {
        this.addgoodsinfo.imgList.splice(imgIndex, 1);
      }
    },
    clearImages1() {
      // 清空图片列表
      this.fileList1 = [];
    },
    clearImages2() {
      // 清空图片列表
      this.fileList2 = [];
    },
    handlePictureCardPreview2(file) {
      this.dialogImageUrl2 = file.url;
      this.dialogVisible2 = true;
    },
    /**图片上传逻辑结束*/
    emitbaseinfo() {
      return this.ruleForm;
    },
    productstatusradiohanle(e) {
      this.productstatusradio = e;
      if (e === "上架") {
        this.addgoodsinfo.goods.status = 1;
      } else {
        this.addgoodsinfo.goods.status = 0;
      }
    },
    checkbox(e) {
      this.addgoodsinfo.goods.attributes = e.join(",");
    }, //商品属性 复选框
    checkboxlabel(e) {}, //商品标签 复选框
    getGoodsTypeList() {
      getCategoryList("isEnabled = 1").then((res) => {
        if (res.code === "00000") {
          this.options = res.data.map((item) => {
            if (item.categoryDTOList && item.categoryDTOList.length > 0) {
              return {
                value: item.id,
                label: item.categoryDTOList[0].categoryName,
                children: item.categoryDTOList.map((subItem) => {
                  return {
                    value: subItem.id,
                    label: subItem.categoryName,
                    // 如果需要，可以添加更多属性
                  };
                }),
              };
            } else {
              // 处理 categoryDTOList 为空的情况，可以根据需求进行适当的处理
              return {
                value: item.id,
                label: item.categoryName,
              };
            }
          });
        }
      });
    }, //商品属性
    optionsID(e) {
      this.addgoodsinfo.goods.parentCategoryId = e[0] || null;
      this.addgoodsinfo.goods.categoryId = e[1] || null;
    }, //选中商品分类
    // 获取商品属性
    getAttribute() {
      getGoodsType({ dictionaryType: "goods_attributes" }).then((res) => {
        this.checkList = res.data;
      });
    },
    isInvoicehandle(e) {
      if (e) {
        this.addgoodsinfo.goods.isInvoice = 1;
      } else {
        this.addgoodsinfo.goods.isInvoice = 0;
      }
    }, //开发票
    exchangepurchasehandle(e) {
      if (e) {
        this.addgoodsinfo.goods.isRejected = 1;
      } else {
        this.addgoodsinfo.goods.isRejected = 0;
      }
    }, //是否支持退换货
    blocksearchhandle(e) {
      if (e) {
        this.addgoodsinfo.goods.isHideSearching = 1;
      } else {
        this.addgoodsinfo.goods.isHideSearching = 0;
      }
    }, //是否屏蔽搜索
  },

  watch: {
    addgoodsinfo: {
      handler(newVal, oldVal) {
        // 当addgoodsinfo发生变化时执行的逻辑
      },
      deep: true, // 如果addgoodsinfo是一个对象，需要加上deep:true
    },
  },
};
</script>
<style scoped></style>
